package edu.uwlax.cs.oayonlinestore.client.gui.shared;

import java.util.Iterator;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;

import edu.uwlax.cs.oayonlinestore.client.OnlinestoreRService;
import edu.uwlax.cs.oayonlinestore.client.utils.ExceptionTool;
import edu.uwlax.cs.oayonlinestore.client.utils.StackPage;
import edu.uwlax.cs.oayonlinestore.vo.CategoryStructureVO;
import edu.uwlax.cs.oayonlinestore.vo.SubcategoryVO;

public class ProductTree extends Tree implements AsyncCallback {

	public class BasicCategoryItem extends TreeItem {
		public BasicCategoryItem(String name, String anchor) {
			super();
			if (anchor == null)
				setWidget(new HTML(name));
			else
				setWidget(new Hyperlink(name, anchor));
		}
	}

	private class CategoryItem extends BasicCategoryItem {
		public CategoryItem(String name, String anchor) {
			super(name, anchor);
			setStyleName(STYLE_CATEGORY_ITEM);
		}
	}

	private class SubCategoryItem extends BasicCategoryItem {
		public SubCategoryItem(String name, String anchor) {
			super(name, anchor);
			setStyleName(STYLE_SUBCATEGORY_ITEM);
		}
	}

	public final static String STYLE_CATEGORY_ITEM = "CategoryItem";

	public final static String STYLE_SUBCATEGORY_ITEM = "SubCategoryItem";

	private StackPage catPage;

	private StackPage subCatPage;

	public ProductTree(StackPage catPage, StackPage subCatPage) {
		super();
		this.catPage = catPage;
		this.subCatPage = subCatPage;
		update();
	}

	public void onFailure(Throwable arg0) {
		Window.alert(ExceptionTool.extractUserMessage(arg0));
	}

	public void onSuccess(Object arg0) {
		CategoryStructureVO[] cat = (CategoryStructureVO[]) arg0;
		for (int i = 0; i < cat.length; i++) {
			String canchor = (catPage != null) ? catPage.getAnchor(cat[i]
					.getId()) : null;
			CategoryItem category = new CategoryItem(cat[i].getTitle(), canchor);
			addItem(category);
			for (Iterator r = cat[i].getSubcategories().iterator(); r.hasNext();) {
				SubcategoryVO sub = (SubcategoryVO) r.next();
				String sanchor = (subCatPage != null) ? subCatPage
						.getAnchor(sub.getId()) : null;
				category.addItem(new SubCategoryItem(sub.getTitle(), sanchor));
			}
		}
	}

	public void update() {
		OnlinestoreRService.Util.getInstance().getCategoryStructureList(this);
	}

}